<?php
/**
 * This is the model class for table "{{user}}".
 *
 * The followings are the available columns in table '{{user}}':
 * @property integer $ID
 * @property string $email
 * @property string $password
 * @property string $name
 * @property string $lastname
 * @property string $city
 * @property string $country
 * @property string $register_date
 * @property string $last_login_date
 */
class User extends CActiveRecord
{
	public $rememberMe=false;
	public $passwordConfirm;
	public $verifyCode;
	
	public $newPassword = '';
	public $newPasswordConfirm = '';
	
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{user}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		return array(
			// Common
			array('email', 'email'),
			array('password, email, name, lastname, city, country', 'length', 'max'=>50),
			array('password, email', 'length', 'min'=>4),
			array('name, lastname, city, country', 'filter', 'filter' => array('CHtml', 'encode')),

			// Login
			array('email, password', 'required', 'on'=>'login'),
			array('password', 'authenticate', 'on'=>'login'),
			array('rememberMe', 'boolean', 'on'=>'login'),
			
			// Update
			array('newPassword', 'isSamePasswords', 'on'=>'update', 'compare'=>'newPasswordConfirm'),
			
			// Register
			array('email, password, passwordConfirm, verifyCode', 'required', 'on'=>'register'),
			array('email', 'emailExists', 'on'=>'register'),
			array('password', 'isSamePasswords', 'on'=>'register', 'compare'=>'passwordConfirm'),
			array('verifyCode', 'captcha', 'on'=>'register'),

			// Search
			array('ID, name, email, register_date, last_login_date', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'ID' => 'ID',
			'login' => 'Логин',
			'password' => 'Пароль',
			'passwordConfirm' => 'Подтверждение пароля',
			'name' => 'Имя',
			'email' => 'E-mail',
			'register_date' => 'Дата регистрации',
			'last_login_date' => 'Дата последнего входа',
			'verifyCode' => 'Код проверки',
			'lastname' => 'Фамилия',
			'city' => 'Город',
			'country' => 'Страна',
			'newPassword' => 'Новый пароль',
			'newPasswordConfirm' => 'Подтверждение нового пароля',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('ID',$this->ID);
        $criteria->compare('email',$this->email,true);
        $criteria->compare('password',$this->password,true);
        $criteria->compare('name',$this->name,true);
        $criteria->compare('lastname',$this->lastname,true);
        $criteria->compare('city',$this->city,true);
        $criteria->compare('country',$this->country,true);
        $criteria->compare('register_date',$this->register_date,true);
        $criteria->compare('last_login_date',$this->last_login_date,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	/**
	 * Аутентификация пользователя
	 */
	public function authenticate($attribute, $params)
    {
        $identity = new UserIdentity($this->email, $this->password);
        if(!$identity->authenticate())
		{
            $this->addError('password', 'Неправильное имя пользователя или пароль.');
		}
		else
		{
			if($this->rememberMe)
			{
				Yii::app()->user->login($identity, 3600*24*7);
			}
			else
			{
				Yii::app()->user->login($identity);
			}
		}
    }
	
	/**
	 * Проверка подтверждения пароля
	 */
	public function isSamePasswords($attribute, $params)
    {
		$compare = $params['compare'];
		
		if(!isset($this->$attribute) || !isset($this->$compare) || $this->$attribute != $this->$compare)
		{
            $this->addError('password', 'Пароли не совпадают');
		}
    }
	
	/**
	 * Проверка существования пользователя с указанным e-mail
	 */
	public function emailExists($attribute, $params)
	{
		$result = User::model()->findByAttributes(array('email' => $this->email));
		if($result !== null)
		{
			$this->addError('email', 'Пользователь с таким e-mail уже существует');
		}
	}
	
	public function getName()
	{
		if(empty($this->name) && empty($this->lastname))
		{
			return $this->email;
		}
		elseif(empty($this->name))
		{
			return $this->lastname;
		}
		else
		{
			return $this->name . ' ' . $this->lastname;
		}
		
	}
	
	protected function beforeSave()
    {
        if(parent::beforeSave())
		{
			if($this->isNewRecord)
			{
				$this->password = crypt($this->password, $this->password);
				$this->register_date = new CDbExpression('NOW()');
			}
			return true;
        }
        return false;
    }
	
	protected function beforeDelete()
    {
        if(parent::beforeDelete())
		{
			$auth = Yii::app()->authManager;
			$authItems = $auth->getAuthItems(null, $this->ID);
			foreach($authItems as $authItem){
				$authItem->revoke($this->ID);
			}
			return true;
        }
        return false;
    }
}